<?php
namespace app\manage\controller;

use support\Request;
use support\View;
use think\facade\Db;
use app\manage\controller\Base;
use app\manage\validate\GoodsValidate;
use app\model\GoodsModel;
use QL\QueryList;
class GoodsController extends Base
{
    public function index(Request $request)
    {
		$key=$request->get('key','');
		View::assign('key', $key);
		$goodsRes=GoodsModel::where('goods_name','like','%'.$key.'%')->order('id DESC')->paginate(['list_rows'=>10,'query'=>request()->all()])->each(function($item, $key){
			$item['cate'] = Db::name('goods_cate')->where('id',$item['cate_id'])->value('name') ?? '其他';
			return $item;
		});
		
		View::assign('goodsRes', $goodsRes);
		View::assign('count1', $goodsRes->total());
        return view('goods/index');
    }
	public function ajax(Request $request)
    {
		$data=$request->post();
		//下面是删除
		if($data['type']=='goods_del'){
			$id=$data['id'];
			if(GoodsModel::destroy($id)){
				return json(['code'=>1]);
			}else{
				return json(['code'=>0]);
			}
		}
		
		if($data['type']=='attr_del'){
			if($w=Db::name('goods_attr')->where('goods_id',$data['id'])->find()){
				Db::name('goods_attr')->delete($w['id']);
				return json(['code'=>1]);
			}
			return json(['code'=>0]);
			
		}
		
		//下面两个是商品的启用和停止
		if($data['type']=='goods_start'){
			if(GoodsModel::where('id',$data['id'])->update(['isopen'=>1])){
				return json(['code'=>1]);
			}else{
				return json(['code'=>0]);
			}
		}
       	if($data['type']=='goods_stop'){
			if(GoodsModel::where('id',$data['id'])->update(['isopen'=>0])){
				return json(['code'=>1]);
			}else{
				return json(['code'=>0]);
			}
		}
		//下面两个是商品的启用和停止
		if($data['type']=='goods_she'){
			if(GoodsModel::where('id',$data['id'])->update(['is_tui'=>1])){
				return json(['code'=>1]);
			}else{
				return json(['code'=>0]);
			}
		}
		if($data['type']=='goods_che'){
			if(GoodsModel::where('id',$data['id'])->update(['is_tui'=>0])){
				return json(['code'=>1]);
			}else{
				return json(['code'=>0]);
			}
		}
		
		if($data['type']=='goods_zhua'){
			if (filter_var($data['url'], FILTER_VALIDATE_URL) !== false) {
				$tempu=parse_url($data['url']);
				$message=$tempu['host'];
				if(substr($message,-6)!='jd.com'){
					return json(['code'=>0,'msg'=>'请抓取京东数据']);
				}
				
				$html = QueryList::get($data['url'])->find('html')->html();
				preg_match("/mainSkuId:'\d*', /", $html, $match1);
				preg_match("/data-id=\"\d*\"/", $html, $match2);
				if(!\is_array($match1) or !\is_array($match2)){
					return json(['code'=>0,'msg'=>'抓取错误']);
				}
				preg_match('/\d+/',$match1[0],$mainSkuId);
				preg_match('/\d+/',$match2[0],$skuId);
				$mainSkuId=$mainSkuId[0];
				$skuId=$skuId[0];
				if($mainSkuId and $skuId){
					$url="https://cd.jd.com/description/channel?skuId=$skuId&mainSkuId=$mainSkuId&charset=utf-8&cdn=2&callback=showdesc";
					$desc= file_get_contents($url);
					$h=json_decode(substr($desc,9,-1),true)["content"];
					$ql = QueryList::html($h);
					$w=$ql->find('img')->attrs('data-lazyload');
					$array =  json_decode( json_encode( $w),true);
					if(empty($array)){
						preg_match_all("/(\/\/img30.360buyimg.com\/\S*)/", $h, $wo);
						if(isset($wo[0])){
							$a=[];
							foreach($wo[0] as $v){
								$a[]=substr($v,0,-2);
							}
							$array=$a;
						}
					}
					return json(['code'=>1,'msg'=>'成功','data'=>$array]);
				}else{
					return json(['code'=>0,'msg'=>'抓取错误']);
				}

			}else{
				return  json(['code'=>0,'msg'=>'url地址不正确']);
			}
		}
		return json(['code'=>0]);
    }
	public function add(Request $request)
    {
    	if(request()->method()=='POST'){
    		$data=$request->post();
			$validate = new GoodsValidate();
			if (!$validate->check($data)) {
			    return view_e($validate->getError());
			}
			if (!isset($data['isopen'])) {
			    $data['isopen']=0;
			} else {
			    $data['isopen']=1;
			}

			$data['goods_code']=time().rand(111111,999999);//商品编号

			$file = $request->file('goods_img');
            if ($file && $file->isValid()  && $file->getSize() >0) {
                if(!in_array($file->getUploadExtension(), ['jpg','png','gif','webp','jpeg'])){return view_e('图片格式不正确');}
                if($file->getSize() > 5*1024*1024){return view_e('图片大小不能超过5M');}
                $path = '/goods/'.date("YmdHis").rand(10000,99999).session('uid', '0').'.'.$file->getUploadExtension();
                $file->move(public_path().$path);
                $data['goods_img']=$path;
            }else{
				return view_e('请添加首页主图！');
			}
			$file = $request->file('goods_list_img');
            if ($file && $file->isValid()  && $file->getSize() >0) {
                if(!in_array($file->getUploadExtension(), ['jpg','png','gif','webp','jpeg'])){return view_e('图片格式不正确');}
                if($file->getSize() > 5*1024*1024){return view_e('图片大小不能超过5M');}
                $path = '/goods/'.date("YmdHis").rand(10000,99999).session('uid', '0').'.'.$file->getUploadExtension();
                $file->move(public_path().$path);
                $data['goods_list_img']=$path;
            }

			$attr_value=str_replace(" ",'',$data['attr_value']);
			$attr_value=str_replace("，", ",", $attr_value);
			$attr_value=implode(",", array_filter(explode(",", $attr_value)));
			$attr_title=$data['attr_title'];
			unset($data['attr_value']);
			unset($data['attr_title']);
			if($goods=GoodsModel::create($data)){
				if($attr_title and $attr_value){
					if($w=Db::name('goods_attr')->where('goods_id',$goods->id)->find()){
						Db::name('goods_attr')->where('id',$w['id'])->update([
							'title'=>$attr_title,
							'value'=>$attr_value,
						]);
					}else{
						Db::name('goods_attr')->insert([
							'goods_id'=>$goods->id,
							'title'=>$attr_title,
							'value'=>$attr_value,
						]);
					}
				}
				return view_s('添加成功了');
			}else{
				return view_e('添加失败了');
			}
    	}
		$cate=Db::name('goods_cate')->where('isopen',1)->order('sort asc')->select();
		View::assign('cate',$cate);

		return view('goods/add');
    }
	public function edit(Request $request)
    {
    	$id=$request->get('id',0);
    	if(request()->method()=='POST'){
    		$data=$request->post();
			$validate = new \app\manage\validate\GoodsValidate;
			if (!$validate->scene('edit')->check($data)) {
			    return view_e($validate->getError());
			}
			$file = $request->file('goods_img');
            if ($file && $file->isValid()  && $file->getSize() >0) {
                if(!in_array($file->getUploadExtension(), ['jpg','png','gif','webp','jpeg'])){return view_e('图片格式不正确');}
                if($file->getSize() > 5*1024*1024){return view_e('图片大小不能超过5M');}
                $path = '/goods/'.date("YmdHis").rand(10000,99999).session('uid', '0').'.'.$file->getUploadExtension();
                $file->move(public_path().$path);
                $data['goods_img']=$path;
            }
			$file = $request->file('goods_list_img');
            if ($file && $file->isValid()  && $file->getSize() >0) {
                if(!in_array($file->getUploadExtension(), ['jpg','png','gif','webp','jpeg'])){return view_e('图片格式不正确');}
                if($file->getSize() > 5*1024*1024){return view_e('图片大小不能超过5M');}
                $path = '/goods/'.date("YmdHis").rand(10000,99999).session('uid', '0').'.'.$file->getUploadExtension();
                $file->move(public_path().$path);
                $data['goods_list_img']=$path;
            }
			if (!isset($data['isopen'])) {
			    $data['isopen']=0;
			} else {
			    $data['isopen']=1;
			}


			$attr_value=str_replace(" ",'',$data['attr_value']);
			$attr_value=str_replace("，", ",", $attr_value);
			$attr_value=implode(",", array_filter(explode(",", $attr_value)));
			$attr_title=$data['attr_title'];
			unset($data['attr_value']);
			unset($data['attr_title']);
			if($attr_title and $attr_value){
				if($w=Db::name('goods_attr')->where('goods_id',$id)->find()){
					Db::name('goods_attr')->where('id',$w['id'])->update([
						'title'=>$attr_title,
						'value'=>$attr_value,
					]);
				}else{
					Db::name('goods_attr')->insert([
						'goods_id'=>$id,
						'title'=>$attr_title,
						'value'=>$attr_value,
					]);
				}
			}

			GoodsModel::where('id',$id)->update($data);		
			return view_s('修改成功了');
    	}
		// 查询当前商品基本信息
        $goods=GoodsModel::where('id',$id)->find();
		View::assign('goods',$goods);
		View::assign('attr',Db::name('goods_attr')->where('goods_id',$id)->find());
		View::assign('cate',Db::name('goods_cate')->where('isopen',1)->order('sort asc')->select());
		return view('goods/edit');
    }
	

}
